package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.deyang.tools.amazon.utils.GlobalConstants;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.conf.ConfigurationBuilder;

public class FollowMoreTwitterUserServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8260454975424643484L;
	private static final Logger log = Logger.getLogger(FollowMoreTwitterUserServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setOAuthConsumerKey("OcVkc2esIUov1HbPEgIwzw")
		  .setOAuthConsumerSecret("s7GcdocDhQBHJqmd9maAgysODcsVitB1vTHxo95KatM")
		  .setOAuthAccessToken("526075693-465aOTK3kP6w6carlGML3cTop7oODlZFNDBgODNO")
		  .setOAuthAccessTokenSecret("ru42xzOf0ypq0ISD5IJ4w8fLDCEdHeXqIw7sLOWtAg");
		cb.setGZIPEnabled(false);
		
		//Get query string for db
		GlobalConstants c = new GlobalConstants();
		String tweetQueryStr = (String) c.getGlobalConfiguration().getProperty(GlobalConstants.TWEET_QUERY_PROPERTY_NAME);
		if (tweetQueryStr == null){
			tweetQueryStr = "source:web kindle";
		}
		Twitter twitter = new TwitterFactory(cb.build()).getInstance();
	    try {
	    	//Remove some followings, to avoide 2000 limitation
	    	long[] ids = twitter.getFriendsIDs(-1).getIDs();
	    	for (int i = 0; i < ids.length && i < 60; i++){
	    		twitter.destroyFriendship(ids[i]);
	    		Thread.sleep(5000);
	    	}
	    	
	    	Query q = new Query(tweetQueryStr);
	    	q.setRpp(100);
	    	q.setPage(1);
	    	QueryResult qr = twitter.search(q);
	    	Iterator<Tweet> it = qr.getTweets().iterator();
	    	while (it.hasNext()){
	    		Tweet t = it.next();
	    		Iterator<User> uit = twitter.searchUsers(t.getFromUser(), 1).iterator();
	    		if (uit.hasNext()){
	    			long id = uit.next().getId();
	    			log.info("Send follow request to user : " + t.getFromUser());
	    			twitter.createFriendship(id,true);
	    			Thread.sleep(5000);
	    		}
	        	
	    	}
	    	resp.setStatus(200);
	    	
		} catch (Exception e) {
			log.warning(e.getMessage());
			e.printStackTrace();
			resp.setStatus(403);
		}
	}
}
